<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>精彩图集</title>
    <link rel="stylesheet" href="/css/computer/index.css">
    <link rel="stylesheet" href="/css/computer/atlas/atlasindex.css">
    <!-- 重置默认样式 -->
    <link rel="stylesheet" href="/css/resetcss.css">
    <style>
        .grid {
            display: grid;
            /* grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); */
            grid-template-columns: repeat(4, 1fr);
            gap: 2rem;
            margin-bottom: 4rem;
        }


        /* 响应式设计 - 在小屏幕上减少列数 */
        @media (max-width: 1200px) {
            .grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 768px) {
            .grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 480px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div class="container-box">
        <div class="sidebar-box-left">
            <div class="sidebar">
                <div class="sidebar-header">
                    <a href="#" class="user" id="user-center">个人中心</a>
					<a href="#" class="user" id="user-login">登录/注册</a>
                </div>
                <nav class="sidebar-nav">
                    <ul>
                        <a class="homepage">
                            <li>主页</li>
                        </a><a href="" class="lifemoment">
                            <li>生活瞬间</li>
                        </a><a href="" class="tourlog">
                            <li>旅行记录</li>
                        </a><a href="" class="atlas">
                            <li class="active">精彩图集</li>
                        </a>
                    </ul>
                </nav>
            </div>
        </div>
        <div class="sidebar-box-right">
            <header>
                <div class="header-content">
                    <h1>记录生活中的美好时刻</h1>
                    <p class="subtitle">珍藏每一份感动，分享每一段旅程</p>
                    <a href="#" class="btn">开始探索</a>
                </div>
            </header>

            <div class="container">
                <h2 class="section-title">精彩图集</h2>
                <div class="grid">
                    <div class="card">
                        <a href="#" class="create-atlas">
                            <div class="card-img">
                                <img src="https://images.unsplash.com/photo-1500051638674-ff996a0ec29e?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80"
                                    alt="四季变换">
                            </div>
                            <div class="card-content">
                                <h3 class="card-title">新建图集</h3>
                                <p class="card-desc">开始创建专属于你的精彩图集。</p>
                                <p class="card-link">
                                    查看详情
                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                        stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M5 12h14M12 5l7 7-7 7"></path>
                                    </svg>
                                </p>
                            </div>
                        </a>
                    </div>
                </div>
            </div>

            <!-- 创建框 -->
            <div class="modal-container" id="customModal">
                <div class="modal-content">
                    <input type="text" class="modal-input" placeholder="请输入...">
                    <button class="modal-submit">提交</button>
                    <button class="modal-close">关闭</button>
                </div>
            </div>

            <footer>
                <div class="footer-links">
                    <a href="#">关于我们</a>
                    <a href="#">联系方式</a>
                    <a href="#">隐私政策</a>
                    <a href="#">使用条款</a>
                </div>
                <p class="copyright">© 2023 美好时光记录 版权所有</p>
            </footer>
        </div>
    </div>
</body>


<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
<script src="/configfile/config.js"></script>
<script src="/script/token.js"></script>
<script type="module">
    //环境变量初始化
    //获取导航的a标签，并设置href
    const homepageElement = document.querySelector('.homepage'); // 返回第一个匹配的节点
    const lifemomentElement = document.querySelector('.lifemoment'); // 返回第一个匹配的节点
    const atlasElement = document.querySelector('.atlas'); // 返回第一个匹配的节点
    const userCenter = document.querySelector('#user-center');//获取个人中心DOM
	const userLogin = document.querySelector('#user-login');//获取登录注册DOM


	let server_ip = window.__ENV__.SERVER_IP;//服务器ip
	let home_ip = window.__ENV__.HOME_SERVER_IP;//首页ip
	homepageElement.href = home_ip;
	let life_ip = window.__ENV__.LIFEMOMENT_SERVER_IP;//生活瞬间
	lifemomentElement.href = life_ip;
	let atlas_ip = window.__ENV__.ATLAS_SERVER_IP;//图片集
	atlasElement.href = atlas_ip;
	let user_ip = window.__ENV__.USER_SERVER_IP;//用户
	userCenter.href = user_ip;
	userLogin.href = user_ip;

	//获取令牌
	let token = localStorage.getItem("token");

	//获取jwt令牌状态
	let jwtState = getJwtState(token);


	if(jwtState.success){
		userCenter.style.display = "block";
		userLogin.style.display = "none";
	}else{
		userCenter.style.display = "none";
		userLogin.style.display = "block";
	}

    //模态框方法
    // 获取DOM元素
    const modal = document.getElementById('customModal');
    const closeBtn = document.querySelector('.modal-close');
    const modalSubmit = document.querySelector('.modal-submit');
    

    // 关闭模态框
    closeBtn.addEventListener('click', () => {
        hideModal();
    });

    // 显示模态框的函数 (对外接口)
    function showModal() {
        modal.classList.add('show');
    }

    // 隐藏模态框的函数 (对外接口)
    function hideModal() {
        modal.classList.remove('show');
    }

    // 点击模态框外部关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            hideModal();
        }
    });

    //获得a标签创建DOM
    let createatlas = document.querySelector(".create-atlas");
    //添加显示函数
    createatlas.addEventListener("click", showModal);

    //添加创建函数
    function createAtlas(){
        let modalInput = document.querySelector(".modal-input");
        let saveData = {
            Atlasname: modalInput.value
        }
        axios
            .post(
                atlas_ip+"/createatlas",
                saveData,
                {
                    headers: {
                        "Authorization": `Bearer ${token}`
                    }
                }
            )
            .then((res) => {
                //判断后端的报错信息。如果存在则保存失败
                console.log(res.data);
                if(res.data.success){
                    alert("创建成功");
                }
                location.reload();
                hideModal();
            })
            .catch(err => {
                console.log(err);
            });
    }
    //绑定创建函数
    modalSubmit.addEventListener("click",createAtlas);

    // 生成卡片函数
    function createCard(cardData) {
        //外壳
        const card = document.createElement('div');
        card.className = 'card';

        let ahref = atlas_ip +"/show" + cardData.Atlas_id;
        card.addEventListener('click', (e) => {
            e.preventDefault();
            axios
                .post(
                    atlas_ip+"/gettempcode",
                    {},
                    {
                        headers: {
                            "Authorization": `Bearer ${token}`
                        }
                    }
                )
                .then((res) => {
                    //判断后端的报错信息。如果存在则保存失败
                    
                    let tempToken = res.data.tempToken;
                    
                    let newWindow = window.open(`${ahref}?tempToken=${tempToken}`, '_blank');
                    // 4. 处理可能的浏览器拦截
                    if (!newWindow || newWindow.closed) {
                        alert("弹出窗口被阻止，请允许网站弹出窗口或手动访问链接。");
                        // 备选方案：当前页跳转
                        window.location.href = `${ahref}?tempToken=${tempToken}`;
                    }
                })
                .catch(err => {
                    console.log(err);
                    alert("拒绝访问");
                });
            
        });

        // 卡片图片部分
        const cardImg = document.createElement('div');
        cardImg.className = 'card-img';

        const img = document.createElement('img');
        img.src = cardData.imageUrl;
        img.alt = cardData.title;
        img.loading = 'lazy'; // 懒加载

        cardImg.appendChild(img);

        // 卡片内容部分
        const cardContent = document.createElement('div');
        cardContent.className = 'card-content';

        const title = document.createElement('h3');
        title.className = 'card-title';
        title.textContent = cardData.title;

        const desc = document.createElement('p');
        desc.className = 'card-desc';
        desc.textContent = cardData.description;

        const link = document.createElement('a');
        link.className = 'card-link';
        link.href = "#";
        link.innerHTML = '查看详情 <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"></path></svg>';

        // 组装卡片内容
        cardContent.appendChild(title);
        cardContent.appendChild(desc);
        cardContent.appendChild(link);

        // 组装完整卡片
        card.appendChild(cardImg);
        card.appendChild(cardContent);

        return card;
    }

    // 渲染所有卡片
    function renderCards(cardsData) {
        // 获取容器元素
        const gridElement = document.querySelector('.grid');
        cardsData.forEach(cardData => {
            const card = createCard(cardData);
            gridElement.appendChild(card);
        });
    }



    //提交后台数据
    (function updataCardsData() {
        let cardsData = [];
        let findData = {
            condition: {},
            limit: {
                skip: 0,
                limit: 0,
                //排序，1正序，-1倒叙
                sort: { Atlascreatedate: -1 }
            }
        };
        //读取上传的图片信息和用户信息
        axios
            .post(
                atlas_ip+"/findatlas",
                findData,
                {
                    headers: {
                        "Authorization": `Bearer ${token}`
                    },
                }
            )
            .then((res) => {
                //判断后端的报错信息。如果存在则保存失败
                if(res.data.message.data.length !== 0){
                    res.data.message.data.forEach(data=>{
                        cardsData.push({
                            Atlas_id: data.Atlas_id,
                            imageUrl: data.Atlascoverurl,
                            title: data.Atlasname,
                            description: data.Atlasmessage
                        });
                    });
                    renderCards(cardsData);
                }else{
                    alert("请创建精彩图集");
                }
                
            })
            .catch(err => {
                console.log(err);
                alert("未登录");
                window.location.href = user_ip + "/loginshow";
            });
    })();



</script>

</html>